<?php
namespace app\api\controller\tbk;
class Tbkitem extends Base
{
    //淘宝客查询商品
    public function lists(){
			if(is_post()){
					$d = $this->post;
					$map = [];
					if($d['keyword']!='') $map[] = ['and','title','like',"%{$d['keyword']}%"];
          if($d['uid']!='') $map[] = ['and','user_id','=',$d['uid']];
					if($d['tbk_cat_id']!='') $map[] = ['and','tbk_cat_id','=',$d['tbk_cat_id']];
					$w  = where($map);
					$sql = "select * from tbk_item $w[0] order by tk_rate desc, update_time desc".limit($d['page'],$d['limit']);
					$rs = $this->db->query($sql, $w[1],'',true);
					if($rs){
              suc($rs[0],$rs[1]);
					}else{
							suc([],0);
					}
			}
    }
    /**
    * 淘宝客详情
    */
    public function detail(){
			if(is_post()){
          $d = $this->post;
          $rule = [
              'uid'=>'require',
              'num_iid'=>'require',
          ];
          $msg = [
          ];
          check($rule,$msg,$d);


          $url = "https://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7Bitem_num_id={$d['num_iid']}%7D";
          $res = file_get_contents($url);
          $res = json_decode($res,true);
          $img = $res['data']['images'];
          $temp = ['img'=>$img];
          //主图, 价格信息
          $rs = $this->db->query("select title,small_images,zk_final_price_wap as zk_final_price,coupon_click_url,volume,reserve_price from tbk_item where user_id=? and num_iid=?",[$d['uid'],$d['num_iid']],1);
          if($rs){
            $rs['small_images'] = array_filter(explode(",",$rs['small_images']));
            $rs['quan_money']   = bcsub($rs['reserve_price'],$rs['zk_final_price'],2);
            $temp['data'] = $rs;
          }else{
            //是否有缓存数据
            $rs_cache = $this->db->query("select content from tbk_search_cache where user_id=? and num_iid=?",[$d['uid'],$d['num_iid']],1);
            if($rs_cache){
              $this->db->query("delete from tbk_search_cache where create_time<?",[time()-20*86400]);
              suc(json_decode($rs_cache['content'],true));
            }

            //接口获取数据
            $user = $this->db->find('user',$d['uid'],'tbk_app_key,tbk_app_secret,tbk_adzone_id');
            $config = [
                'appkey' => $user['tbk_app_key'],
                'secretKey' => $user['tbk_app_secret'],
                'format' => 'json',
                'sandbox' => false,
            ];
            $app = m('Tbk','c')->getApp($config);
            //淘宝客商品详情（简版）
            $data = [
              'num_iids' => $d['num_iid'],
            ];
            $result = $app->item->getInfo($data);
            $title = $result->results->n_tbk_item[0]->title;
            $data = [
              'q' => $title,
              'page_no'=>1,
              'page_size'=>1,
              'platform'=>2,
              'sort'=>'total_sales_desc',
              'adzone_id'=>$user['tbk_adzone_id'],
              'has_coupon'=>'true',
              'need_free_shipment'=>'true',
              'need_prepay'=>'true',
              'include_pay_rate_30'=>'true',
              'include_good_rate'=>'true',
              'include_rfd_rate'=>'true',
              'npx_level'=>2,
            ];
            $res = $app->dg->materialOptional($data);
            $res = json_encode($res);
            $res = json_decode($res,true);
            $res = isset($res['result_list']) && isset($res['result_list']['map_data'])?$res['result_list']['map_data']:[];
            $con = $res[0];
            $rs = [
               'title'=>$con['title'],
               'small_images'=>$con['small_images']['string'],
               'zk_final_price'=>$con['zk_final_price'],
               'coupon_click_url'=>"https:".$con['coupon_share_url'],
               'volume'=>$con['volume'],
               'reserve_price'=>$con['reserve_price'],
            ];
            $rs['quan_money']   = bcsub($rs['reserve_price'],$rs['zk_final_price'],2);
            $temp['data'] = $rs;
            $cache_data = [
              'user_id'=>$d['uid'],
              'num_iid'=>$d['num_iid'],
              'content'=>json_encode($temp,JSON_UNESCAPED_UNICODE),
              'create_time'=>time()
            ];
            $this->db->insert('tbk_search_cache', $cache_data);
          }
          suc($temp);
			}
    }
    /**
    * 生成淘口令
    */
    public function tkpwd(){
			if(is_post()){
          $d = $this->post;
          $rule = [
            'num_iid'=>'require',
            'uid'=>'require',
          ];
          $msg = [
          ];
          check($rule,$msg,$d);
          $user = $this->db->find('user', $d['uid'], "tbk_app_key,tbk_app_secret");
          $config = [];
          if($user){
            $config = [
                'appkey' => $user['tbk_app_key'],
                'secretKey' => $user['tbk_app_secret'],
            ];
          }
          $app = m('Tbk','c')->getApp($config);
          //淘宝客商品三方分成链接转换
          // $data = [
          //   "fields"=>"num_iid,click_url,commission_rate,coupon_amount,coupon_click_url",
          //   "num_iids"=>$d['num_iid'],
          //   "sub_pid"=>"mm_16174063_19172048_1374690897", //pid,
          //   "platform"=>1,
          //   "unid"=>1,
          //   "adzone_id"=>1374690897
          // ];
          // $rs = $app->item->convert($data);
          //转淘口令
          $data = [
            'text'=>rand(10000,99999),
            'url'=>$d['coupon_click_url'],
          ];
          $rs = $app->tpwd->create($data);
          $pwd = $rs->data->model;
          suc(['pwd'=>$pwd]);
			}
    }

    /**
    * 搜索页面: 阿里妈妈通用物料-导购
    **/
    public function search(){
        if(is_post()){
            $d = $this->post;
            $rule = [
                'keyword'=>'require',
                'page' => 'require',
                'limit' => 'require',
            ];
            $msg = [
            ];
            check($rule,$msg,$d);
            //接口获取数据
            $user = $this->db->find('user',$d['uid'],'tbk_app_key,tbk_app_secret,tbk_adzone_id');
            $config = [
                'appkey' => $user['tbk_app_key'],
                'secretKey' => $user['tbk_app_secret'],
                'format' => 'json',
                'sandbox' => false,
            ];
            $app = m('Tbk','c')->getApp($config);
            $data = [
              'q' => $d['keyword'],
              'page_no'=>$d['page'],
              'page_size'=>$d['limit'],
              'platform'=>2,
              'sort'=>'total_sales_desc',
              'adzone_id'=>$user['tbk_adzone_id'],
              'has_coupon'=>'true',
              'need_free_shipment'=>'true',
              'need_prepay'=>'true',
              'include_pay_rate_30'=>'true',
              'include_good_rate'=>'true',
              'include_rfd_rate'=>'true',
              'npx_level'=>2,
            ];
            $res = $app->dg->materialOptional($data);
            $res = json_encode($res);
            $res = json_decode($res,true);
            $res = isset($res['result_list']) && isset($res['result_list']['map_data'])?$res['result_list']['map_data']:[];
            suc($res);
        }
    }
}
